//
//  ZQBaseDao.m
//  ZQSmartLife
//
//  Created by huanghuan on 15/6/10.
//  Copyright (c) 2015年 huanghuan. All rights reserved.
//

#import "ZQBaseDao.h"
#import "ZQModel.h"

@implementation ZQBaseDao

-(id) init
{
    self = [super init];
    if (self) {
        self.tableName = @"device";
    }
    return self;
}

-(BOOL) executeUpdate:(NSString *)sql
{
    NSLog(@"sql:%@",sql);
    BOOL ret = [[ZQDBHelper sharedInstance] execSql:sql];
    return ret;
}

-(BOOL) executeMutiUpdate:(NSMutableArray *) sqlArray{
    return [[ZQDBHelper sharedInstance] execMultipleSql:sqlArray];
}

-(sqlite3_stmt *) query:(NSString *) sql
{
    NSLog(@"%@",sql);
    return [[ZQDBHelper sharedInstance] query:sql];
}


/**
 根据条件查询 无条件即传nil
 @param condStr 条件
 @return 返回对应的model 列表,如果没有查到，则返回空数组,返回nil,查询失败
 */
-(NSArray *) getItemsByCondStr:(NSString *) condStr
{
    NSString *sql = [NSString stringWithFormat:@"select * from %@ ",_tableName];
    if (condStr){
        sql = [sql stringByAppendingString:@"where "];
        sql = [sql stringByAppendingString:condStr];
    }
    _statement = [self query:sql];
    if (_statement){
        id result = [self parseStatement];
        sqlite3_finalize(_statement);
        return result;
    }
    else{
        return nil;
    }
}

/**
 插入
 @param lists 数据库对象列表
 @param return 所有数据插入成功则返回YES，否则返回NO,插入失败后会回滚
 */
-(BOOL) insertItems:(NSArray *) lists
{
    NSMutableArray *sqlArray = [NSMutableArray arrayWithCapacity:0];
    for(id model in lists){
       NSString *sql =  [self getInsertStringWithModel:model];
        [sqlArray addObject:sql];
    }
    return [self executeMutiUpdate:sqlArray];
}
/**
 删除
 @param itemLists 数据库对象列表,根据ID删除
 @param return 所有数据删除成功则返回YES，否则返回NO,删除失败后会回滚
 */
-(BOOL) deleteItems:(NSArray *) lists
{
    return YES;
}

#pragma -mark 获取语句
//获取插入语句
-(NSString *) getInsertStringWithModel:(id) model
{
    NSDictionary *dict = nil;
    if ([model respondsToSelector:@selector(dictionary)]) {
        dict = [model dictionary];
    }
    if (dict == nil) {
        return nil;
    }
    NSString *sql = [NSString stringWithFormat:@"insert into %@(",_tableName];
    int index = 0;
    NSArray *dictKeysArr = [dict allKeys];
    for(NSString *key in dictKeysArr){
        index++;
        if (index == dictKeysArr.count){
            sql = [NSString stringWithFormat:@"%@%@)",sql,key];
        }
        else{
            sql = [NSString stringWithFormat:@"%@%@,",sql,key];
        }
    }
    index = 0;
    sql = [NSString stringWithFormat:@"%@ values(",sql];
    for(NSString *key in dictKeysArr){
        index ++;
        if (index == dictKeysArr.count){
            sql = [NSString stringWithFormat:@"%@%@)",sql,[self getColumnValueFormat:[dict objectForKey:key]]];
        }
        else{
            sql = [NSString stringWithFormat:@"%@%@,",sql,[self getColumnValueFormat:[dict objectForKey:key]]];
        }
    }
     return sql;
}


#pragma -mark 解析参数
-(NSString *)getColumnValueFormat:(id) value
{
    if ([value isKindOfClass:[NSString class]]){
        return [NSString stringWithFormat:@"'%@'",value];
    }
    else{
        return value;
    }
}
-(NSString *)bindColumn:(NSString *)columnName  value:(id) value
{
    if ([value isKindOfClass:[NSString class]]){
        return [NSString stringWithFormat:@"%@ = '%@'",columnName,value];
    }
    else{
        return [NSString stringWithFormat:@"%@ = %@",columnName,value];
    }
}

#pragma 查询结果解析
-(id) parseStatement
{
    return nil;
}


#pragma -mark 解析列
-(NSString *) stringForColumn:(NSString *) columnName
{
    return [self stringForColumnIndex:[self columnIndexForName:columnName]];
}

-(int) intForColumn:(NSString *) columnName
{
    return [self intForColumnIndex:[self columnIndexForName:columnName]];
}
-(float) floatForColumn:(NSString *) columnName
{
    return [self floatForColumnIndex:[self columnIndexForName:columnName]];
}

-(NSUInteger) int64ForColumn:(NSString *) columnName
{
    return [self uintegerForColumnIndex:[self columnIndexForName:columnName]];
}

-(NSString *) stringForColumnIndex:(int) columnIdx
{
    if (sqlite3_column_type(_statement, columnIdx) == SQLITE_NULL || (columnIdx < 0)) {
        return nil;
    }
    
    const char *c = (const char *)sqlite3_column_text(_statement, columnIdx);
    
    if (!c) {
        // null row.
        return nil;
    }
    
    return [NSString stringWithUTF8String:c];
}



-(int) intForColumnIndex:(int) columnIdx
{
    return sqlite3_column_int(_statement, columnIdx);
}

-(float) floatForColumnIndex:(int) columnIndx
{
    return sqlite3_column_double(_statement, columnIndx);
}


-(NSUInteger) uintegerForColumnIndex:(int) columnIndx
{
    return sqlite3_column_int64(_statement, columnIndx);
}
- (NSMutableDictionary *)columnNameToIndexMap
{
    if (!_columnNameToIndexMap) {
        int columnCount = sqlite3_column_count(_statement);
        _columnNameToIndexMap = [[NSMutableDictionary alloc] initWithCapacity:(NSUInteger)columnCount];
        int columnIdx = 0;
        for (columnIdx = 0; columnIdx < columnCount; columnIdx++) {
            [_columnNameToIndexMap setObject:[NSNumber numberWithInt:columnIdx]
                                      forKey:[[NSString stringWithUTF8String:sqlite3_column_name(_statement, columnIdx)] lowercaseString]];
        }
    }
    return _columnNameToIndexMap;
}

- (int)columnIndexForName:(NSString*)columnName
{
    columnName = [columnName lowercaseString];
    if (!_columnNameToIndexMap)
    {
        [self columnNameToIndexMap];
    }
    NSNumber *n = [_columnNameToIndexMap objectForKey:columnName];
    
    if (n) {
        return [n intValue];
    }
    NSLog(@"Warning: I could not find the column named '%@'.", columnName);
    
    return -1;
}


@end
